#
import os

from flask import Flask
from flask.logging import default_handler
import logging
from logging.handlers import RotatingFileHandler
import click

from .config.settings import config
from .extensions import db, migrate
from .api import api_bp


def create_app(config_name=None):
    if not config_name:
        config_name = os.getenv('FLASK_CONFIG', 'development')
    app = Flask(__name__)
    app.config.from_object(config[config_name])

    register_logging(app)
    register_extensions(app)
    register_blueprints(app)
    register_request_handlers(app)
    register_template_context(app)
    register_errors(app)
    register_commands(app)
    register_shell_context(app)

    return app


def register_logging(app):
    # 注册日志模块
    app.logger.setLevel(logging.INFO)
    formatter = logging.Formatter(
        '%(asctime)s - %(pathname)s:%(lineno)d [%(levelname)s] %(module)s:%(funcName)s - %(message)s')
    if not app.debug:
        log_path = os.getenv('LOG_PATH', 'logs/app.log')
        file_handler = RotatingFileHandler(
            log_path, maxBytes=10 * 1024 * 1024, backupCount=7, encoding='utf-8')
        file_handler.setFormatter(formatter)
        file_handler.setLevel(logging.INFO)
        app.logger.addHandler(file_handler)
    else:
        default_handler.setFormatter(formatter)
        default_handler.setLevel(logging.DEBUG)
        app.logger.addHandler(default_handler)


def register_extensions(app):
    # 注册扩展模块
    db.init_app(app)
    migrate.init_app(app, db)


def register_blueprints(app):
    # 注册蓝图
    app.register_blueprint(api_bp, url_prefix='/api')


def register_request_handlers(app):
    # 注册请求处理模块
    pass


def register_template_context(app):
    # 注册模板上下文
    pass


def register_errors(app):
    # 注册错误异常
    @app.errorhandler(Exception)
    def handle_exception(e):
        return e


def register_commands(app):
    # 注册命令
    @app.cli.command()
    @click.option('--username', help='username')
    @click.option('--password', help='password')
    def login(username, password):
        '''
        Test cli command
        '''
        if username:
            click.echo(f"Hi {username}, your password is: {password}")
        click.echo(f"Hi Stranger!")


def register_shell_context(app):
    # 注册shell环境
    @app.shell_context_processor
    def make_shell_context():
        return dict()
